﻿
using DataService.Data;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace UnitTest
{
    public class TestSnowflake
    {
        public void TestTryParse()
        {
            var f = new Snowflake();
            var id = f.NewId();
            Console.WriteLine($"ID*：{id}");
            var time = id >> 22;
            Console.WriteLine($"毫秒:{time}");
            var tt = f.StartTimestamp.AddMilliseconds(time);
            Console.WriteLine($"生成ID时间:{time}");

            var wid = (id >> 12) & 0x3FF;
            Console.WriteLine($"机器号：{wid}");

            var seq = id & 0x0FFF;
            Console.WriteLine($"序列号：{seq}");
            //Assert.Equal(f.Sequence, seq);

            // 时间转编号
            var id2 = f.GetId(tt);
            Console.WriteLine($"Id2值：{id2},id2长度：{id2.ToString().Length},id长度：{id.ToString().Length}");
            // 分析
            var rs = f.TryParse(id, out var t, out var w, out var s);

            Console.WriteLine($"解析结果：{rs}，时间：{t},机器号：{w},序列号：{s}");
            Console.WriteLine($"构建业务ID：{f.NewId(tt)}");


        }
        public void Test2()
        {
            var sw = Stopwatch.StartNew();
            // var count =1000;
            long count = 100_000L;


            int length = Environment.ProcessorCount;
            List<long> snowList = new List<long>((int)count * length);
            Console.WriteLine($"Environment.ProcessorCount：{length}");
            var ts = new List<Task>();
            for (var i = 0; i < length; i++)
            {
                ts.Add(Task.Run(() =>
                {
                    var f = new Snowflake();
                    for (var n = 0; n < count; n++)
                    {
                      
                        var id = f.NewId();
                        snowList.Add(id);
                        // Console.WriteLine(id);
                    }
                }));
            }

            Task.WaitAll(ts.ToArray());

            sw.Stop();

            count *= ts.Count;
            Console.WriteLine(string.Format("生成 {0:n0}，耗时 {1}，速度 {2:n0}tps", count, sw.Elapsed, count * 1000 / sw.ElapsedMilliseconds));

            Console.WriteLine($"总长度：{snowList.Count}，去重长度：{snowList.Distinct().ToList().Count}");
            foreach (var item in snowList.Take(50))
            {
                Console.WriteLine(item);
            }


        }
    }
}
